{-# LANGUAGE OverloadedStrings #-}

import Data.List
import Text.LaTeX
import Text.LaTeX.Base.Class
import Text.LaTeX.Base.Syntax
import Text.LaTeX.Packages.Graphicx
import Text.LaTeX.Packages.Geometry
import Util
import Vec

main :: IO ()
main = printdoc doc

doc :: Monad m => LaTeXT_ m
doc = do
    mapM_ rendere $ polymap (vadd (0.0, 0.0, 1.0)) $ polyrotate (icosahedron 1) (0.0, 0.3, 0.3)

rendere :: LaTeXC l => (Vec3, Vec3) -> l
rendere (a, b) =
    if d > 0.001 then textblock' (vw $ fst c) (vw $ snd c) $ rotatebox' (-t * 180 / pi) $ fontsize (vw $ d * 0.092) (vw 0) "Ceci n'est pas un icosaèdre"
    else ""
  where
    c = vadd a' $ vdiv (vsub b' a') 2
    d = vdist a' b'
    t = atan2 (snd $ vsub b' a') (fst $ vsub b' a')
    a' = vadd (0.5, sqrt 2 / 2) $ vproject a
    b' = vadd (0.5, sqrt 2 / 2) $ vproject b

polymap :: (Vec3 -> Vec3) -> [(Vec3, Vec3)] -> [(Vec3, Vec3)]
polymap f = fmap (\(a, b) -> (f a, f b))

polyrotate :: [(Vec3, Vec3)] -> Vec3 -> [(Vec3, Vec3)]
polyrotate vs t = polymap (flip v3rotate t) vs

icosahedron :: Double -> [(Vec3, Vec3)]
icosahedron r = connect dist $ vicosahedron r
  where
    connect dist xs = [(x, y) | (x:ys) <- tails xs, y <- ys, vdist x y < dist]
    dist = r * 2.02 / vmag (phi, 1.0 :: Double)

vicosahedron :: Double -> [Vec3]
vicosahedron r = fmap (flip vdiv $ (vmag (phi, 1.0 :: Double)) / r) $ c vs
  where
    c = (\vs -> vs ++ (fmap (vcycle . vcycle) vs) ++ (fmap vcycle vs))
    vs = [(x, y, z) | x <- [-1, 1], y <- [0], z <- [phi, -phi]]

phi :: Double
phi = (1 + sqrt 5) / 2
